//
//  ZXView.m
//  折线图
//
//  Created by iOS on 16/6/28.
//  Copyright © 2016年 iOS. All rights reserved.
//

#import "CCChartLineView.h"

#define xyTitleLabelFont  10
@interface CCChartLineView ()

@property (nonatomic, strong) CAShapeLayer *lineChartLayer;
@property (nonatomic, strong)UIBezierPath * path1;

/*折线所在区域的视图 */
@property (nonatomic, strong) UIView *gradientBackgroundView;
@property (nonatomic, assign) CGFloat maxLengthForYTitle; //y轴title最长字符串的长度
@property (nonatomic, assign) CGFloat labelHeight;     //label的高度

@property (nonatomic, strong) NSMutableArray *xTitles;
@property (nonatomic, strong) NSMutableArray *yTitles;
@property (nonatomic, strong) NSString *titleLBText;

@end
@implementation CCChartLineView
static CGFloat bounceX = 20;
static CGFloat bounceY = 20;
static NSInteger countq = 0;
static CGFloat margin = 10;
#define randomColor [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]
-(NSMutableArray *)yTitles{
    if (_yTitles == nil) {
        
        _yTitles = [NSMutableArray array];
    }
    return _yTitles;
}

-(NSMutableArray *)xTitles{
    if (_xTitles == nil) {
        
        _xTitles = [NSMutableArray array];
    }
    return _xTitles;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
     //   self.my
        self.backgroundColor = [UIColor whiteColor];
        self.titleLBText = @"折线图";
        
        for (int i = 0; i < 6; i ++) {
            
            [self.yTitles addObject:[NSString stringWithFormat:@"%d",i*100]];
        }
        for (int i = 0; i < 6; i ++) {
            
            [self.xTitles addObject:[NSString stringWithFormat:@"%d月",i+1]];
        }

        //找出最长字符串的宽度
        [self maxLengthForY_title];
        
        //创建界面
        [self setupUI];

        [self createLabelX];
        [self createLabelY];
        [self setLine];
          }
    return self;
}

#pragma mark - 添加x y轴 边缘的线
//- (void)drawRect:(CGRect)rect{
//       /*******画出坐标轴********/
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetLineWidth(context, 2.0);
//    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
//    CGContextMoveToPoint(context, bounceX, bounceY);
//    CGContextAddLineToPoint(context, bounceX, rect.size.height - bounceY);
//    CGContextAddLineToPoint(context,rect.size.width -  bounceX, rect.size.height - bounceY);
//    CGContextStrokePath(context);
//    
//      }

#pragma mark 添加虚线
- (void)setLine{

    //横轴的线条
    for (NSInteger i = 0;i < _yTitles.count; i++ ) {
        
        UILabel * yLabel = (UILabel*)[self viewWithTag:2000 + i];
        CGRect lineFrame = CGRectMake(self.gradientBackgroundView.frame.origin.x, 0, self.gradientBackgroundView.frame.size.width, 0.5);
        UIView *line = [self lineViewWithFrame:lineFrame];
        line.center = CGPointMake(line.center.x, yLabel.center.y);

    }
    
    //纵轴的线条
    for (NSInteger i = 0;i < _xTitles.count; i++ ) {
        
        UILabel * xLabel = (UILabel*)[self viewWithTag:1000 + i];
        CGRect lineFrame = CGRectMake(xLabel.frame.origin.x + (xLabel.frame.size.width - 5) / 2, 0, 5, self.gradientBackgroundView.frame.size.height + self.gradientBackgroundView.frame.origin.y);
        UIView *line = [self lineViewWithFrame:lineFrame];
        line.backgroundColor = [UIColor redColor];
//        line.center = CGPointMake(xLabel.center.x, line.center.y);
//        NSLog(@"line.center.x == %f,line.center.y = %f",line.center.x,line.center.y);
    }

}

#pragma mark - 线条
-(UIView*)lineViewWithFrame:(CGRect)frame{

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(self.gradientBackgroundView.frame.origin.x, 0, self.gradientBackgroundView.frame.size.width, 0.5)];
    line.backgroundColor = [UIColor brownColor];
    [self addSubview:line];
 
    return line;
}
#pragma mark 画折线图
- (void)dravLine{
    
    UILabel * label = (UILabel*)[self viewWithTag:1000];
    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 1.0;
    self.path1 = path;
    UIColor * color = [UIColor greenColor];
    [color set];
    [path moveToPoint:CGPointMake( label.frame.origin.x - bounceX, (600 -arc4random()%600) /600.0 * (self.frame.size.height - bounceY*2 )  )];

    //创建折现点标记
    NSArray *values = @[@"300",@"50",@"600",@"100",@"320",@"150"];
    for (NSInteger i = 1; i< values.count; i++) {
        
        UILabel * xLabel = (UILabel*)[self viewWithTag:1000 + i];
        NSLog(@"xLabel.center.x == %f",xLabel.center.x);
//        CGFloat  arc = arc4random()%600;
        NSString *yStr = values[i];
        NSInteger y = yStr.integerValue;
        [path addLineToPoint:CGPointMake(xLabel.frame.origin.x + xLabel.frame.size.width / 2,  y /600.0 * self.gradientBackgroundView.frame.size.height)];
        
//        UILabel * falglabel = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x , (600 -arc) /600.0 * (self.frame.size.height - bounceY*2 )+ bounceY  , 30, 15)];
//      //  falglabel.backgroundColor = [UIColor blueColor];
//        falglabel.tag = 3000+ i;
//        falglabel.text = [NSString stringWithFormat:@"%.1f",arc];
//        falglabel.font = [UIFont systemFontOfSize:8.0];
//        [self addSubview:falglabel];
    }
    // [path stroke];
    
    self.lineChartLayer = [CAShapeLayer layer];
    self.lineChartLayer.path = path.CGPath;
    self.lineChartLayer.strokeColor = [UIColor redColor].CGColor;
    self.lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默认设置路径宽度为0，使其在起始状态下不显示
    self.lineChartLayer.lineWidth = 0;
    self.lineChartLayer.lineCap = kCALineCapRound;
    self.lineChartLayer.lineJoin = kCALineJoinRound;
    
    [self.gradientBackgroundView.layer addSublayer:self.lineChartLayer];//直接添加导视图上
 //   self.gradientBackgroundView.layer.mask = self.lineChartLayer;//添加到渐变图层

}
#pragma mark 创建x轴的数据
- (void)createLabelX{
    
    CGFloat xWidth = _gradientBackgroundView.frame.size.width / self.xTitles.count;
    UILabel *xLabel;
    for (NSInteger i = 0; i < self.xTitles.count; i++) {
        
        CGRect labelXFrame = CGRectMake(self.maxLengthForYTitle + i * xWidth, _gradientBackgroundView.frame.size.height + _gradientBackgroundView.frame.origin.y , xWidth, self.labelHeight);
        
       xLabel = [self creatLBWithFrame:labelXFrame
                          text:self.xTitles[i]
                           tag:1000 + i
                 textAlignment:NSTextAlignmentCenter];
        xLabel.backgroundColor = randomColor;
    }
    
    CGFloat y = xLabel.frame.origin.y + xLabel.frame.size.height;
    UILabel *titleLB = [self creatLBWithFrame:CGRectMake(0, y, self.bounds.size.width, 20)                     text:self.titleLBText
                                          tag:-1
                                textAlignment:NSTextAlignmentCenter];
    titleLB.backgroundColor = [UIColor purpleColor];
    titleLB.font = [UIFont systemFontOfSize:14];


}
#pragma mark 创建y轴数据
- (void)createLabelY{
    
    CGFloat heightSpace = (_gradientBackgroundView.frame.size.height - self.labelHeight * self.yTitles.count) / self.yTitles.count;
    CGFloat viewHeight = _gradientBackgroundView.frame.size.height;
    
    for (NSInteger i = 0; i < _yTitles.count; i++) {
        
        CGRect labelFrame = CGRectMake(0, viewHeight - self.labelHeight / 2 - i * (self.labelHeight + heightSpace), self.maxLengthForYTitle, self.labelHeight);
       [ self creatLBWithFrame:labelFrame
                          text:_yTitles[i]
                           tag:2000 + i
                 textAlignment:NSTextAlignmentRight];
    }
}

-(UILabel*)creatLBWithFrame:(CGRect)frame
                       text:(NSString*)text
                        tag:(NSInteger)tag
              textAlignment:(NSTextAlignment)textAlignment
{

    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = [UIFont systemFontOfSize:xyTitleLabelFont];
    label.tag = tag;
    label.textAlignment = textAlignment;
    label.backgroundColor = [UIColor blueColor];
    [self addSubview:label];
    
    return label;
}

#pragma mark 初始化界面
- (void)setupUI {
    // 背景视图（不包含坐标轴）
    CGFloat w = self.frame.size.width - self.maxLengthForYTitle;
    
    self.gradientBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(self.maxLengthForYTitle, 0, w, self.bounds.size.height - 40)];
    self.gradientBackgroundView.backgroundColor = [UIColor yellowColor];
    [self addSubview:self.gradientBackgroundView];

}
#pragma mark - y轴最长字符串的长度
-(void)maxLengthForY_title{
    
    NSString *firstYTitle = _yTitles[0];
    self.maxLengthForYTitle = [self sizeForTitle:firstYTitle].width;
    self.labelHeight = [self sizeForTitle:firstYTitle].height;
    
    for (int i = 1; i < _yTitles.count; i++) {
        
        NSString *title = _yTitles[i];
        
       CGSize textSize = [self sizeForTitle:title];
        self.labelHeight = textSize.height;
        CGFloat width = textSize.width;
        
        if (self.maxLengthForYTitle <= width)
            self.maxLengthForYTitle = width;
    }
}
#pragma mark - 计算字符串的宽度
-(CGSize)sizeForTitle:(NSString*)title{

    NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:xyTitleLabelFont]};
    CGSize size = CGSizeMake(200, 2000);
    CGRect frame = [title boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];

    return frame.size;
}
#pragma mark 点击重新绘制折线和背景
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    countq++;
    if (countq%2 == 0) {
        [self.lineChartLayer removeFromSuperlayer];
        for (NSInteger i = 0; i < 12; i++) {
            UILabel * label = (UILabel*)[self viewWithTag:3000 + i];
            [label removeFromSuperview];
        }
    }else{

        [self dravLine];

    self.lineChartLayer.lineWidth = 2;
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 3;
    pathAnimation.repeatCount = 1;
    pathAnimation.removedOnCompletion = YES;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    // 设置动画代理，动画结束时添加一个标签，显示折线终点的信息
    pathAnimation.delegate = self;
    [self.lineChartLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
        //[self setNeedsDisplay];
    }
}
- (void)animationDidStart:(CAAnimation *)anim{
    NSLog(@"开始®");
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    NSLog(@"停止~~~~~~~~");
}
@end
